from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.ext import db
import atom.url
import gdata.contacts.service
import gdata.alt.appengine
import settings
import cgi
import liveboarddb


class Auth(webapp.RequestHandler):
  
    def get(self):
        gid = self.request.get('gid')
          
        client = gdata.contacts.service.ContactsService()
        gdata.alt.appengine.run_on_appengine(client)

        auth_token = gdata.auth.extract_auth_sub_token_from_url(self.request.uri)

        if auth_token:
            self.response.out.write("""auth_token: %s <br>""" % auth_token)
            session_token = client.upgrade_to_session_token(auth_token)
            
            if session_token and users.get_current_user():
                self.response.out.write("""session_token: %s <br>""" % session_token)
                client.token_store.add_token(session_token)
            elif session_token:
                self.response.out.write("""session_token2: %s <br>""" % session_token)
                client.current_token = session_token
                
            if gid:
              path = "/index.html?gid=%s" % gid
            else:
              path = "/index.html"
            main_url = atom.url.Url('http', settings.HOST_NAME, path=path)
            self.redirect(str(main_url))

        #else ask for authorization
        else:
            if gid:
              path = "/auth?gid=%s" % gid
            else:
              path = "/auth"

            next_url = atom.url.Url('http', settings.HOST_NAME, path=path)
            auth_uri = client.GenerateAuthSubURL(next_url,
                ('http://docs.google.com/feeds/','http://www.google.com/m8/feeds',), secure=False, session=True)
            self.redirect(str(auth_uri))


def main():
    application = webapp.WSGIApplication([('/auth', Auth),], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
